package com.linchuansi.lock.condition;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * *
 *
 * @author wb
 * @date 2025-11-12 22:39*@since 1.0.0
 */
public class ConditionDemo {
    volatile  static int i=10;
    public static void main(String[] args) {
        //extracted();
        new Thread()
        {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("开始执行子线程");
                i=11;
            }
        }.start();
        while(i==10)
        {
            LockSupport.park(Thread.currentThread());
        }
    }

    private static void extracted() {
        ConditionDemo conditionDemo = new ConditionDemo();
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        conditionDemo.test(lock,condition);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("尝试获取一次锁"+lock.tryLock());
        System.out.println("结束执行主线程");
        System.out.println("休眠一会");
        condition.signal();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.unlock();
        System.out.println("尝试再次获取锁");
        System.out.println(lock.tryLock());
        System.out.println("结束执行主线程");
    }

    void test(ReentrantLock lock, Condition condition)
    {
        System.out.println("开始执行主线程");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread thread = new Thread()
        {
            @Override
            public void run() {
                System.out.println("开始执行子线程");
                lock.lock();
                System.out.println(Thread.currentThread().getName());
                try {
                    System.out.println("子线程开始等待");
                    condition.await();
                    System.out.println("子线程等待结束");
                } catch (InterruptedException e) {
                    System.out.println("子线程被中断");
                    e.printStackTrace();
                }
                lock.unlock();
            }
        };
        thread.start();
    }
}
